using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using CommunityToolkit.Mvvm.Messaging;
using DialogHostAvalonia;
using Microsoft.Extensions.DependencyInjection;
using MsBox.Avalonia;
using MsBox.Avalonia.Dto;
using MsBox.Avalonia.Models;
using SchoolApp.Msgs;
using SchoolApp.ViewModels;

namespace SchoolApp.Views;

public partial class TeacherMgrView : UserControl
{
    public TeacherMgrView()
    {
        InitializeComponent();
        DataContext = Program.ServiceProvider.GetRequiredService<TeacherMgrViewModel>();
    }

    private void TeacherMgrView_Loaded(object sender, RoutedEventArgs e)
    {
        WeakReferenceMessenger.Default.Register<MsgBase<TeacherViewModel>>(this, async (r, msg) =>
        {
            var formEditViewModel = Program.ServiceProvider.GetRequiredService<TeacherEditViewModel>();
            formEditViewModel.InitData(msg.Data);
            var result = await DialogHost.Show(
                new TeacherEditView { DataContext = formEditViewModel },
                "MainWindowHost");
            if (result is true)
            {
                if (msg.Data.Id == 0)
                {
                    //新增
                }
                else
                {
                    //修改
                }

                btnQuery.Command?.Execute(null);
            }
        });
        WeakReferenceMessenger.Default.Register<TeacherDelMsg>(this, async (r, msg) =>
        {
            var messageBox = MessageBoxManager.GetMessageBoxCustom(
                new MessageBoxCustomParams
                {
                    ContentTitle = "删除提示",
                    ContentMessage = $"确认要删除[{msg.Teacher.Code}]数据记录吗",
                    ButtonDefinitions =
                    [
                        new ButtonDefinition() { Name = "确定" },
                        new ButtonDefinition() { Name = "取消", IsDefault = true, IsCancel = true }
                    ],
                    Icon = MsBox.Avalonia.Enums.Icon.Warning,
                    WindowStartupLocation = WindowStartupLocation.CenterScreen, // 居中显示
                    Topmost = true, 
                });
            var result = await messageBox.ShowWindowDialogAsync(Program.MainWindow);
            if (result == "确定")
            {
                msg.Execute?.Invoke();
            }
        });
        btnQuery.Command?.Execute(null);
    }

    private void TeacherMgrView_Unloaded(object sender, RoutedEventArgs e)
    {
        WeakReferenceMessenger.Default.Unregister<MsgBase<TeacherViewModel>>(this);
    }
}